package com.yuan.blog.controller;
import com.yuan.blog.service.InvitataionScoreService;
import com.yuan.blog.utils.R;
import com.yuan.blog.entity.CommentEntity;
import com.yuan.blog.entity.UserEntity;
import com.yuan.blog.exception.JsonException;
import com.yuan.blog.service.ICommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/CommentController")
public class CommentController{

    @Autowired
    private ICommentService commentService;

    @Autowired
    private InvitataionScoreService scoreService;


    @PostMapping("/add/{id}")
    public String add(@PathVariable("id") Integer id, CommentEntity commentEntity, HttpServletRequest req) throws Exception {
        UserEntity loginUser = (UserEntity) req.getSession().getAttribute("loginUser");
        if (loginUser == null) {
//            return R.error("请先登录");
            throw new JsonException(100,"请先登录");
        }

        // 1.获取表单数据
//        Map<String, String[]> parameterMap = req.getParameterMap();

        // 2.准备实体类
//        CommentEntity commentEntity = new CommentEntity();

        // 3.把Map中的数据拷贝到实体类中
//        BeanUtils.populate(commentEntity, parameterMap);

        // 4.入库
        commentEntity.setUserId(loginUser.getId());
        commentService.save(commentEntity);

// 3.评论的数量改变了把帖子id写到redis中，需要计算分数了
        if (commentEntity.getEntityType() == 1) { // 只有给帖子做评论时采取计算
            scoreService.addIdToRedis(id);
        }


        // 5.重定向当前帖子下面
//        return BaseConstants.BASE_REDIRECT+":InvitationController/info/"+commentEntity.getEntityId();
//        return R.ok();
        return "redirect:/InvitationController/info/" +id;
    }
}
